<template>
	<a-drawer
		:title="formData.id ? '编辑' : '新增'"
		:width="800"
		:visible="visible"
		:destroy-on-close="true"
		:footer-style="{ textAlign: 'right' }"
		@close="onClose"
	>
		<a-form ref="formRef" :model="formData">
			<a-row :gutter="16">
				<a-col :span="24">
					<a-form-item label="帮助标题" name="subject" :rules="required('请输入标题')">
						<a-input v-model:value="formData.subject" placeholder="请输入标题" />
					</a-form-item>
				</a-col>
			</a-row>

			<a-row>
				<a-col :span="24">
					<a-form-item label="帮助内容" name="content" :rules="required('请输入标题')">
						<hp-editor v-model="formData.content" :toolbar="toolbar" placeholder="请输入帮助内容"></hp-editor>
					</a-form-item>
				</a-col>
			</a-row>
		</a-form>
		<template #footer>
			<a-button style="margin-right: 8px" @click="onSubmit('0')" :loading="submitLoading">保存</a-button>
			<a-button type="primary" @click="onSubmit('1')" :loading="submitLoading">提交</a-button>
		</template>
	</a-drawer>
</template>

<script setup name="loginMessageForm">
import { cloneDeep } from 'lodash-es'
import { required } from '@/utils/formRules'
import HpEditor from '@/components/Editor/index.vue'
import loginMessageApi from '@/api/biz/loginMessageApi'

const toolbar = ref(
	'undo redo | forecolor bold italic underline | formatselect fontselect fontsizeselect | \
				alignleft aligncenter alignright alignjustify outdent indent lineheight | bullist numlist | \
				image preview'
)
// 抽屉状态
const visible = ref(false)
const emit = defineEmits({ successful: null })
const formRef = ref()
// 表单数据
const formData = ref({})
const submitLoading = ref(false)

// 打开抽屉
const onOpen = (record) => {
	visible.value = true
	if (record) {
		let recordData = cloneDeep(record)
		formData.value = Object.assign({}, recordData)
	}
}
// 关闭抽屉
const onClose = () => {
	formRef.value.resetFields()
	formData.value = {}
	visible.value = false
}

// 验证并提交数据
const onSubmit = (status) => {
	formRef.value.validate().then(() => {
		submitLoading.value = true
		const formDataParam = cloneDeep(formData.value)
		formDataParam.status = status
		console.log(formDataParam)
		loginMessageApi
			.loginMessageSubmitForm(formDataParam, !formDataParam.id)
			.then(() => {
				onClose()
				emit('successful')
			})
			.finally(() => {
				submitLoading.value = false
			})
	})
}
// 抛出函数
defineExpose({
	onOpen
})
</script>
<style>
.mce-content-body p img {
	max-width: 80%;
	width: auto;
	height: auto;
}
</style>
